package com.fanjia.taobao.security;


import com.fanjia.taobao.user.dao.RoleDao;
import com.fanjia.taobao.user.entity.User;
import com.fanjia.taobao.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author codermy
 * @createTime 2020/7/16
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleDao roleDao;




    @Override
    public User loadUserByUsername(String userName){
        // 根据用户名获取用户
        User user = userService.queryByUsername(userName);
        if (user == null ){
            throw new BadCredentialsException("用户名或密码错误");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        //List<MenuIndexDto> list = menuDao.listByUserId(user.getUserId());
        List<String> collect = roleDao.queryRoleByUserId(user.getId());
        for (String authority : collect){
            if (!("").equals(authority) & authority !=null){

                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(authority);
                grantedAuthorities.add(grantedAuthority);
            }
        }
        user.setAuthorities(grantedAuthorities);
        return user;
    }


}